<!--  -->
<template>
  <div class="">
    <crumb  title="首页" title2="用户管理" title3="用户列表"></crumb >
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            clearable
            v-model="queryInfo.query"
            @clear="getData"
          >
            <el-button slot="append" icon="el-icon-search" @click="getData"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>
      <template>
        <el-table :data="tableData" stripe style="width: 100%">
          <el-table-column prop="id" label="编号" width="60"> </el-table-column>
          <el-table-column prop="username" label="用户名"> </el-table-column>
          <el-table-column prop="mobile" label="手机号" > </el-table-column>
          <el-table-column prop="role_name" label="角色" > </el-table-column>
          <el-table-column label="状态" >
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.mg_state"
                @change="userstateChange(scope.row)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column prop="email" label="邮箱" > </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
             <el-button type="primary" icon="el-icon-edit" circle @click="handleUpdate(scope.row)"></el-button>
             <el-button type="danger" icon="el-icon-delete" circle @click="handleDelete(scope.row)"></el-button>
              <el-button type="warning" icon="el-icon-star-off" circle @click="handleQuanx(scope.row)"></el-button>
            
            </template>
          </el-table-column>
        </el-table>
      </template>
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[2, 3, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="add">确 定</el-button>
      </span>
    </el-dialog>

    <el-dialog
      title="编辑用户"
      :visible.sync="dialogVisible1"
      width="50%"
      :before-close="handleClose1"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm1"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose1">取 消</el-button>
        <el-button type="primary" @click="updataadd">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="分配角色"
      :visible.sync="dialogVisible2"
      width="30%"
      :before-close="handleClose2"
    >
      <el-form :model="roles" label-width="100px">
        <el-form-item label="当前用户">
          {{ roles.username }}
        </el-form-item>
        <el-form-item label="当前角色">
          {{ roles.role_name }}
        </el-form-item>
        <el-form-item label="分配新角色">
          <el-select v-model="roles.region" placeholder="请选择">
            <el-option
              v-for="(item, index) in options"
              :key="item.index"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="this.handleClose2">取 消</el-button>
        <el-button type="primary" @click="Quanxslec">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    var validatePass = (rule, value, callback) => {
      const regmodel = /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (regmodel.test(value)) {
        return callback();
      } else {
        callback(new Error("请输入正确的手机号"));
      }
    };
    //这里存放数据
    return {
      total: 0,
      id: 0,
      yongh_id:0,
      roles: {
        username: "",
        role_name: "",
        region: "",
      },
      options: [],
      tableData: [],
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 3,
      },
      ruleForm: {
        email: "",
        username: "",
        mobile: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入名称", trigger: "blur" },
          { min: 3, max: 10, message: "长度在 3 到 10 个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 15, message: "长度在 6到 15 个字符", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: validatePass, trigger: "blur" },
        ],
      },
      dialogVisible: false,
      dialogVisible1: false,
      dialogVisible2: false,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    async handleQuanx(row) {
      console.log(row.id)
      this.yongh_id=row.id
      this.dialogVisible2 = true;
      this.roles = row;
      const { data: res } = await this.myaxios.get(`roles`);
      this.options=res.data;
    },
   async Quanxslec() {
      console.log(this.roles.region)
       const { data: res } = await this.myaxios.put(`users/${this.yongh_id}/role`,
        {
          rid:this.roles.region
        }
       );
       if (res.meta.status !== 200) {
        this.$message.error("失败！");
      } else {
        this.$message.success("成功！");
      }
      this.getData()
      this.handleClose2()
       
    },
    async userstateChange(data) {
      const { data: res } = await this.myaxios.put(
        `users/${data.id}/state/${data.mg_state}`
      );
      if (res.meta.status !== 200) {
        data.mg_state = !data.mg_state;
        this.$message.error("更新用户状态失败！");
      } else {
        this.$message.success("更新用户状态成功！");
      }
    },
    async handleDelete(row) {
      const { data: res } = await this.myaxios.delete(`users/${row.id}`);
      if (res.meta.status !== 200) {
        this.$message.error("删除用户失败！");
      } else {
        this.$message.success("删除用户成功！");
        this.getData();
      }
    },
    handleUpdate(row) {
      this.dialogVisible1 = true;
      console.log(row.id);
      this.id = row.id;
      this.ruleForm = row;
    },
    async updataadd() {
      console.log(this.id);
      const { data: res } = await this.myaxios.put(`users/${this.id}`, this.ruleForm);
      if (res.meta.status !== 200) {
        this.$message.error("编辑用户失败！");
      } else {
        this.$message.success("编辑用户成功！");
      }
      this.handleClose1();
      this.getData();
    },
    handleSizeChange(size) {
      this.queryInfo.pagenum = 1;
      this.queryInfo.pagesize = size;
      this.getData();
    },
    handleCurrentChange(num) {
      this.queryInfo.pagenum = num;
      this.getData();
    },
    handleClose1() {
      this.dialogVisible1 = false;
      this.$refs.ruleForm1.resetFields();
    },
    handleClose() {
      this.dialogVisible = false;
      this.$refs.ruleForm.resetFields();
    },
    handleClose2() {
      this.dialogVisible2 = false;
    },
    add() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.myaxios.post("users", this.ruleForm);
        if (res.meta.status !== 201) {
          this.$message.error("添加用户失败！");
        }
        if (res.meta.status == 400) {
          this.$message.error(res.meta.message);
        }
        this.$message.success("添加用户成功!");
        this.handleClose();
        this.getData();
      });
    },
    async getData() {
      const { data: res } = await this.myaxios.get("users", {
        params: this.queryInfo,
      });
      console.log(res);
      this.tableData = res.data.users;
      this.total = res.data.total;
      
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.getData();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped></style>
